package com.shortlink.common.util;

import jakarta.annotation.Resource;
import lombok.Setter;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

/**
 * 布隆过滤器工具类
 *
 * @author wp
 */
@ConditionalOnClass(RedissonClient.class)
@Component
@Setter
public class RBloomFilterUtils {
    /**
     * 默认预计插入数量
     */
    private static final long EXPECTED_INSERTIONS = 200000000L;
    /**
     * 默认误判率
     */
    private static final double FALSE_PROBABILITY = 0.001;
    @Resource
    private RedissonClient redissonClient;

    public <T> RBloomFilter<T> create(String key) {
        RBloomFilter<T> bloomFilter = redissonClient.getBloomFilter(key);
        bloomFilter.tryInit(EXPECTED_INSERTIONS, FALSE_PROBABILITY);
        return bloomFilter;
    }

    public <T> RBloomFilter<T> create(String key, long expectedInsertions, double falseProbability) {
        RBloomFilter<T> bloomFilter = redissonClient.getBloomFilter(key);
        bloomFilter.tryInit(expectedInsertions, falseProbability);
        return bloomFilter;
    }
}
